package com.travel.travel_springboot_web.service;

import com.travel.travel_springboot_web.entity.Order;
import com.travel.travel_springboot_web.entity.OrderGoods;
import com.travel.travel_springboot_web.entity.Goods;
import com.travel.travel_springboot_web.entity.Cart;
import com.travel.travel_springboot_web.mapper.GoodsMapper;
import com.travel.travel_springboot_web.mapper.OrderMapper;
import com.travel.travel_springboot_web.mapper.CartMapper;
import com.travel.travel_springboot_web.mapper.OrderGoodsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class OrderService {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private GoodsMapper goodsMapper;
    
    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    
    public List<Order> getOrderList(Long userId, Integer status, Integer role, String keyword, String startDate, String endDate) {
        try {
            // 如果是管理员，可以查看所有订单
            if (role == 2) {  // 2: 管理员
                if (status == null) {
                    return orderMapper.findAllWithSearch(keyword, startDate, endDate);
                }
                return orderMapper.findByStatusWithSearch(status, keyword, startDate, endDate);
            }
            
            // 普通用户只能查看自己的订单
            if (status == null) {
                return orderMapper.findByUserIdWithSearch(userId, keyword, startDate, endDate);
            }
            
            // 验证状态值
            if (status != 1 && status != 2 && status != 3) {
                throw new RuntimeException("无效的订单状态");
            }
            
            return orderMapper.findByUserIdAndStatusWithSearch(userId, status, keyword, startDate, endDate);
        } catch (Exception e) {
            logger.error("Error getting order list: ", e);
            throw new RuntimeException("获取订单列表失败: " + e.getMessage());
        }
    }
    
    @Transactional
    public void cancelOrder(Long orderId, Long userId) {
        try {
            // 1. 获取订单信息
            Order order = orderMapper.findById(orderId, userId);
            if (order == null) {
                throw new RuntimeException("订单不存在");
            }
            
            // 2. 检查订单状态
            if (order.getStatus() != 1) {  // 只有未完成的订单可以取消
                throw new RuntimeException("已完成或已取消的订单不可取消");
            }
            
            // 3. 更新订单状态为已取消
            if (!orderMapper.updateStatus(orderId, userId, 3)) {  // 3表示已取消
                throw new RuntimeException("取消订单失败");
            }
            
            // 4. 恢复商品库存
            for (OrderGoods orderGoods : order.getOrderGoods()) {
                // 计算需要恢复的总数量（购买数量 + 赠送数量）
                int totalNum = orderGoods.getNum() + orderGoods.getGiftNum();
                
                // 恢复库存
                if (!goodsMapper.increaseStock(orderGoods.getGoodsId(), totalNum)) {
                    throw new RuntimeException("恢复商品库存失败");
                }
                
                logger.info("Restored stock for goods: {}, amount: {}", 
                    orderGoods.getGoodsId(), totalNum);
            }
            
            logger.info("Order canceled successfully: {}", orderId);
        } catch (Exception e) {
            logger.error("Error canceling order: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    public Order getOrderDetail(Long orderId, Long userId, Integer role) {
        try {
            Order order;
            // 管理员可以查看所有订单
            if (role == 2) {  // 2: 管理员
                order = orderMapper.findByIdForAdmin(orderId);
            } else {
                // 普通用户只能查看自己的订单
                order = orderMapper.findByIdAndUserId(orderId, userId);
            }
            
            if (order == null) {
                throw new RuntimeException("订单不存在");
            }
            
            logger.info("Got order detail: {}, for user: {}, role: {}", orderId, userId, role);
            return order;
        } catch (Exception e) {
            logger.error("Error getting order detail: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    public Map<String, Integer> getOrderStats(Long userId, Integer role) {
        try {
            Map<String, Integer> stats = new HashMap<>();
            
            // 管理员查看所有订单统计
            if (role == 2) {  // 2: 管理员
                stats.put("total", orderMapper.countAll());  // 全部订单
                stats.put("pending", orderMapper.countByStatus(1));  // 待收货(未完成)
                stats.put("completed", orderMapper.countByStatus(2));  // 已完成
                stats.put("canceled", orderMapper.countByStatus(3));  // 已取消
            } else {
                // 普通用户只能查看自己的订单统计
                stats.put("total", orderMapper.countByUserId(userId));  // 全部订单
                stats.put("pending", orderMapper.countByUserIdAndStatus(userId, 1));  // 待收货(未完成)
                stats.put("completed", orderMapper.countByUserIdAndStatus(userId, 2));  // 已完成
                stats.put("canceled", orderMapper.countByUserIdAndStatus(userId, 3));  // 已取消
            }
            
            logger.info("Order stats for user {}, role {}: {}", userId, role, stats);
            return stats;
        } catch (Exception e) {
            logger.error("Error getting order stats: ", e);
            throw new RuntimeException("获取订单统计失败: " + e.getMessage());
        }
    }

    @Transactional
    public void restoreOrder(Long orderId, Long userId) {
        try {
            // 1. 获取订单信息
            Order order = orderMapper.findById(orderId, userId);
            if (order == null) {
                throw new RuntimeException("订单不存在");
            }
            
            // 2. 检查订单状态
            if (order.getStatus() != 3) {  // 只有已取消的订单可以恢复
                throw new RuntimeException("只有已取消的订单可以恢复");
            }
            
            // 3. 检查商品库存
            for (OrderGoods orderGoods : order.getOrderGoods()) {
                // 计算需要的总数量（购买数量 + 赠送数量）
                int totalNum = orderGoods.getNum() + orderGoods.getGiftNum();
                
                // 检查商品是否存在且上架
                Goods goods = goodsMapper.findById(orderGoods.getGoodsId());
                if (goods == null || goods.getStatus() != 1) {
                    throw new RuntimeException("商品" + orderGoods.getGoodsTitle() + "已下架");
                }
                
                // 检查库存是否足够
                if (goods.getStock() < totalNum) {
                    throw new RuntimeException("商品" + orderGoods.getGoodsTitle() + "库存不足");
                }
            }
            
            // 4. 扣减库存
            for (OrderGoods orderGoods : order.getOrderGoods()) {
                int totalNum = orderGoods.getNum() + orderGoods.getGiftNum();
                if (!goodsMapper.decreaseStock(orderGoods.getGoodsId(), totalNum)) {
                    throw new RuntimeException("扣减商品库存失败");
                }
                logger.info("Decreased stock for goods: {}, amount: {}", 
                    orderGoods.getGoodsId(), totalNum);
            }
            
            // 5. 更新订单状态为未完成
            if (!orderMapper.updateStatusFromCanceled(orderId, userId, 1)) {  // 1表示未完成
                throw new RuntimeException("恢复订单失败");
            }
            
            logger.info("Order restored successfully: {}", orderId);
        } catch (Exception e) {
            logger.error("Error restoring order: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    @Transactional
    public void confirmOrder(Long orderId, Long userId, String customerName, String addressName, String deliveryConfirmedBy, Integer role) {
        try {
            // 1. 获取订单信息 - 管理员可以确认任何订单
            Order order;
            if (role == 2) { // 管理员角色
                order = orderMapper.findByIdForAdmin(orderId);
            } else {
                order = orderMapper.findByIdAndUserId(orderId, userId);
            }
            
            if (order == null) {
                throw new RuntimeException("订单不存在");
            }

            // 2. 根据角色更新不同的确认状态
            if (role == 1) { // 客户角色
                // 检查是否已确认
                if (order.getCustomerStatus() == 1) {
                    throw new RuntimeException("订单已确认，请勿重复操作");
                }
                // 更新客户确认信息
                order.setCustomerConfirmedAt(LocalDateTime.now());
                order.setCustomerStatus(1);
                order.setCustomer(customerName);
                logger.info("Customer confirmed order: {}, customer: {}", orderId, customerName);
            } else if (role == 2) { // 送货员/管理员角色
                // 检查是否已确认
                if (order.getDeliveryStatus() == 1) {
                    throw new RuntimeException("订单已确认，请���重复操作");
                }
                // 更新送货员确认信息
                order.setDeliveryConfirmedAt(LocalDateTime.now());
                order.setDeliveryStatus(1);
                order.setDeliveryPerson(deliveryConfirmedBy);
                logger.info("Delivery person confirmed order: {}, delivery person: {}", orderId, deliveryConfirmedBy);
            } else {
                throw new RuntimeException("无效的用户角色");
            }

            // 3. 更新订单确认状态 - 管理员可以更新任何订单
            boolean updated;
            if (role == 2) {
                updated = orderMapper.updateOrderConfirmationStatusByAdmin(orderId,
                        order.getCustomerStatus(), order.getDeliveryStatus(),
                        order.getDeliveryPerson(), order.getCustomer(),
                        order.getDeliveryConfirmedAt(), order.getCustomerConfirmedAt());
            } else {
                updated = orderMapper.updateOrderConfirmationStatus(orderId, userId,
                        order.getCustomerStatus(), order.getDeliveryStatus(),
                        order.getDeliveryPerson(), order.getCustomer(),
                        order.getDeliveryConfirmedAt(), order.getCustomerConfirmedAt());
            }
            
            if (!updated) {
                throw new RuntimeException("更新订单确认状态失败");
            }

            // 4. 检查是否双方都已确认，如果是则更新订单状态为已完成
            if (order.getDeliveryStatus() == 1 && order.getCustomerStatus() == 1) {
                boolean statusUpdated;
                if (role == 2) {
                    statusUpdated = orderMapper.updateOrderStatusByAdmin(orderId, 2); // 2表示已完成
                } else {
                    statusUpdated = orderMapper.updateOrderStatus(orderId, userId, 2);
                }
                if (!statusUpdated) {
                    throw new RuntimeException("更新订单状态失败");
                }
                logger.info("Order completed as both parties confirmed: {}", orderId);
            }

            logger.info("Order confirmation updated successfully: {}", orderId);
        } catch (Exception e) {
            logger.error("Error confirming order: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    @Transactional
    public Order checkout(Long userId, String deliveryPerson, String customer) {
        try {
            // 1. 获取购物车中的商品
            List<Cart> selectedCarts = cartMapper.findByUserId(userId);
            if (selectedCarts.isEmpty()) {
                throw new RuntimeException("购物车为空");
            }

            // 2. 创建订单对象
            Order order = new Order();
            order.setUserId(userId);
            order.setOrderNo(generateOrderNo());
            order.setConfirmed(0); // 初始状态为未确认
            order.setDeliveryPerson(deliveryPerson); // 设置送货员
            order.setCustomer(customer); // 设置客户

            // 3. 计算总价和订单商品列表
            List<OrderGoods> orderGoodsList = new ArrayList<>();
            BigDecimal totalPrice = BigDecimal.ZERO;

            for (Cart cart : selectedCarts) {
                Goods goods = goodsMapper.findById(cart.getGoodsId());
                if (goods == null || goods.getStatus() != 1) {
                    throw new RuntimeException("商品" + cart.getGoodsTitle() + "已下架");
                }

                // 检查库存
                if (goods.getStock() < cart.getNum()) {
                    throw new RuntimeException("商品" + cart.getGoodsTitle() + "库存不足");
                }

                // 创建订单商品
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setGoodsId(cart.getGoodsId());
                orderGoods.setGoodsTitle(goods.getTitle());
                orderGoods.setGoodsImage(goods.getCoverImage());
                orderGoods.setGoodsPrice(goods.getPrice());
                orderGoods.setNum(cart.getNum());
                orderGoods.setTotalPrice(goods.getPrice().multiply(new BigDecimal(cart.getNum())));
                orderGoodsList.add(orderGoods);
                totalPrice = totalPrice.add(orderGoods.getTotalPrice());
            }

            order.setTotalPrice(totalPrice);

            // 4. 保存订单
            orderMapper.insert(order);

            // 5. 保存订单商品
            for (OrderGoods orderGoods : orderGoodsList) {
                orderGoods.setOrderId(order.getId());
                orderGoodsMapper.insert(orderGoods);
            }

            // 6. 删除已结算的购物车商品
            for (Cart cart : selectedCarts) {
                cartMapper.delete(cart.getId(), userId);
            }

            // 7. 返回完整的订单信息（包含地址和商品详情）
            return orderMapper.findById(order.getId(), userId);
        } catch (Exception e) {
            logger.error("Checkout failed: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    private String generateOrderNo() {
        return String.format("%s%06d", 
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                (int)(Math.random() * 1000000));
    }

    @Transactional
    public Order getOrderDetails(Long orderId, Long userId, Integer role) {
        try {
            Order order;
            // 管理员可以查看所有订单
            if (role != null && role == 2) {  // 2: 管理员
                order = orderMapper.findByIdForAdmin(orderId);
            } else {
                // 普通用户只能查看自己的订单
                order = orderMapper.findByIdAndUserId(orderId, userId);
            }
            
            if (order == null) {
                throw new RuntimeException("订单不存在");
            }
            return order;
        } catch (Exception e) {
            logger.error("Error getting order details: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }
} 